//
//  Login.m
//  KYRR
//
//  Created by kyjun on 15/11/2.
//
//

#import "Login.h"
#import "WXApi.h"
#import "MMember.h"
#import "Register.h"

#import "AppDelegate.h"


@interface Login ()

@property(nonatomic,strong) UIView* headerView;
@property(nonatomic,strong) UIButton* btnTop;
@property(nonatomic,strong) UITextField* txtUserName;
@property(nonatomic,strong) UITextField* txtPassword;
@property(nonatomic,strong) UIButton* btnLogin;
@property(nonatomic,strong) UIButton* btnRegister;

@property(nonatomic,strong) UIView* footerView;
@property(nonatomic,strong) UILabel* labelTitle;
@property(nonatomic,strong) UIImageView* leftLine;
@property(nonatomic,strong) UIImageView* rightLine;
@property(nonatomic,strong) UIButton* btnQQ;
@property(nonatomic,strong) UIButton* btnWeChat;
@property(nonatomic,strong) TencentOAuth*  tencentOAuth;

@end

@implementation Login

-(instancetype)init{
    self = [super init];
    if(self){
        [self layoutNav];
    }
    return  self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"登录";
    [self layoutUI];
    [self layoutConstraints];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(weChatLoginAuthorization:) name:NotificatonWXLoginAuthorization object:nil];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(![WXApi isWXAppInstalled]){
        self.btnWeChat.hidden=YES;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark =====================================================  UI布局
-(void)layoutNav{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeView:)];
}

-(void)layoutUI{
    self.headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 280.f)];
    self.btnTop = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnTop.backgroundColor = theme_navigation_color;
    [self.btnTop setTitle:@"主人欢迎回家" forState:UIControlStateNormal];
    [self.btnTop setTitleColor:theme_default_color forState:UIControlStateNormal];
    [self.headerView addSubview:self.btnTop];
    
    UILabel* label = [[UILabel alloc]init];
    label.frame = CGRectMake(0, 0, 5, 45);
    
    self.txtUserName = [[UITextField alloc]init];
    self.txtUserName.placeholder = @"请输入用户名";
    self.txtUserName.backgroundColor = theme_default_color;
    self.txtUserName.borderStyle=UITextBorderStyleNone;
    self.txtUserName.layer.borderColor =theme_line_color.CGColor;
    self.txtUserName.layer.borderWidth = 1.0f;
    self.txtUserName.layer.masksToBounds = YES;
    self.txtUserName.layer.cornerRadius = 5.f;
    self.txtUserName.leftView = label;
    self.txtUserName.leftViewMode =UITextFieldViewModeAlways;
    self.txtUserName.font = [UIFont systemFontOfSize:14.f];
    [self.headerView addSubview:self.txtUserName];
    
    label = [[UILabel alloc]init];
    label.frame = CGRectMake(0, 0, 5, 45);
    UIButton* btn  =[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 21, 13);
    [btn setContentEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 5)];
    [btn setImage:[UIImage imageNamed:@"icon-secure"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(switchTouch:) forControlEvents:UIControlEventTouchUpInside];
    self.txtPassword = [[UITextField alloc]init];
    self.txtPassword.backgroundColor = theme_default_color;
    self.txtPassword.secureTextEntry = YES;
    self.txtPassword.placeholder = @"请输入密码";
    self.txtPassword.borderStyle=UITextBorderStyleNone;
    self.txtPassword.layer.borderColor =theme_line_color.CGColor;
    self.txtPassword.font = [UIFont systemFontOfSize:14.f];
    self.txtPassword.layer.borderWidth = 1.0f;
    self.txtPassword.layer.masksToBounds = YES;
    self.txtPassword.layer.cornerRadius = 5.f;
    self.txtPassword.leftView = label;
    self.txtPassword.leftViewMode =UITextFieldViewModeAlways;
    self.txtPassword.rightView = btn;
    self.txtPassword.rightViewMode = UITextFieldViewModeAlways;
    [self.headerView addSubview:self.txtPassword];
    
    self.btnLogin = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnLogin.backgroundColor = theme_navigation_color;
    [self.btnLogin setTitleColor:theme_default_color forState:UIControlStateNormal];
    [self.btnLogin setTitle:@"登录" forState:UIControlStateNormal];
    [self.btnLogin addTarget:self action:@selector(btnLoginTouch:) forControlEvents:UIControlEventTouchUpInside];
    self.btnLogin.layer.masksToBounds = YES;
    self.btnLogin.layer.cornerRadius = 5.f;
    self.btnLogin.layer.borderColor = theme_line_color.CGColor;
    [self.headerView addSubview:self.btnLogin];
    
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"免费注册"];
    NSRange strRange = {0,[str length]};
    [str addAttribute:NSForegroundColorAttributeName value:theme_title_color range:strRange];
    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
    
    self.btnRegister = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.btnRegister setTitleColor:theme_Fourm_color forState:UIControlStateNormal];
    [self.btnRegister setAttributedTitle:str forState:UIControlStateNormal];
    [self.btnRegister addTarget:self action:@selector(registerTouch:) forControlEvents:UIControlEventTouchUpInside];
    self.btnRegister.titleLabel.font = [UIFont systemFontOfSize:14.f];
    self.btnRegister.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.headerView addSubview:self.btnRegister];
    
    self.footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
    self.leftLine = [[UIImageView alloc]init];
    self.leftLine.backgroundColor = theme_Fourm_color;
    [self.footerView addSubview:self.leftLine];
    
    self.labelTitle = [[UILabel alloc]init];
    self.labelTitle.text = @"其他登录方式";
    self.labelTitle.textColor = theme_Fourm_color;
    self.labelTitle.font = [UIFont systemFontOfSize:14.f];
    self.labelTitle.textAlignment = NSTextAlignmentCenter;
    [self.footerView addSubview:self.labelTitle];
    
    self.rightLine =[[UIImageView alloc]init];
    self.rightLine.backgroundColor = theme_Fourm_color;
    [self.footerView addSubview:self.rightLine];
    
    self.btnQQ = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.btnQQ setImage:[UIImage imageNamed:@"icon-qq"] forState:UIControlStateNormal];
    [self.btnQQ addTarget:self action:@selector(QQLoginTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.footerView addSubview:self.btnQQ];
    
    self.btnWeChat = [ UIButton buttonWithType:UIButtonTypeCustom];
    [self.btnWeChat setImage:[UIImage imageNamed:@"icon-wechat"] forState:UIControlStateNormal];
    [self.btnWeChat addTarget:self action:@selector(weiXinLoginTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.footerView addSubview: self.btnWeChat];
    
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableHeaderView = self.headerView;
    // self.tableView.tableFooterView = self.footerView;
    
    
}

-(void)layoutConstraints{
    self.btnTop.translatesAutoresizingMaskIntoConstraints = NO;
    self.txtUserName.translatesAutoresizingMaskIntoConstraints = NO;
    self.txtPassword.translatesAutoresizingMaskIntoConstraints = NO;
    self.btnLogin.translatesAutoresizingMaskIntoConstraints = NO;
    self.btnRegister.translatesAutoresizingMaskIntoConstraints = NO;
    self.labelTitle.translatesAutoresizingMaskIntoConstraints  = NO;
    self.btnQQ.translatesAutoresizingMaskIntoConstraints =NO ;
    self.btnWeChat.translatesAutoresizingMaskIntoConstraints = NO;
    self.leftLine.translatesAutoresizingMaskIntoConstraints  = NO;
    self.rightLine.translatesAutoresizingMaskIntoConstraints = NO;
    
    
    [self.btnTop addConstraint:[NSLayoutConstraint constraintWithItem:self.btnTop attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:40.f]];
    [self.btnTop addConstraint:[NSLayoutConstraint constraintWithItem:self.btnTop attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:SCREEN_WIDTH]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.btnTop attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.headerView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.f]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.btnTop attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.headerView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.f]];
    
    [self.txtUserName addConstraint:[NSLayoutConstraint constraintWithItem:self.txtUserName attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:40.f]];
    [self.txtUserName addConstraint:[NSLayoutConstraint constraintWithItem:self.txtUserName attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:SCREEN_WIDTH-20]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.txtUserName attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.btnTop attribute:NSLayoutAttributeBottom multiplier:1.0 constant:15.f]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.txtUserName attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.headerView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:10.f]];
    
    
    [self.txtPassword addConstraint:[NSLayoutConstraint constraintWithItem:self.txtPassword attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:40.f]];
    [self.txtPassword addConstraint:[NSLayoutConstraint constraintWithItem:self.txtPassword attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:SCREEN_WIDTH-20]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.txtPassword attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.txtUserName attribute:NSLayoutAttributeBottom multiplier:1.0 constant:15.f]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.txtPassword attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.headerView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:10.f]];
    
    [self.btnLogin addConstraint:[NSLayoutConstraint constraintWithItem:self.btnLogin attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:40.f]];
    [self.btnLogin addConstraint:[NSLayoutConstraint constraintWithItem:self.btnLogin attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:SCREEN_WIDTH-20]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.btnLogin attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.txtPassword attribute:NSLayoutAttributeBottom multiplier:1.0 constant:15.f]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.btnLogin attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.headerView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:10.f]];
    
    [self.btnRegister addConstraint:[NSLayoutConstraint constraintWithItem:self.btnRegister attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:40.f]];
    [self.btnRegister addConstraint:[NSLayoutConstraint constraintWithItem:self.btnRegister attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:80.f]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.btnRegister attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.btnLogin attribute:NSLayoutAttributeBottom multiplier:1.0 constant:10.f]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.btnRegister attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.headerView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:10.f]];
    
    [self.leftLine addConstraint:[NSLayoutConstraint constraintWithItem:self.leftLine attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:0.5f]];
    [self.leftLine addConstraint:[NSLayoutConstraint constraintWithItem:self.leftLine attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:SCREEN_WIDTH/3]];
    [self.footerView addConstraint:[NSLayoutConstraint constraintWithItem:self.leftLine attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.footerView attribute:NSLayoutAttributeTop multiplier:1.0 constant:20.f]];
    [self.footerView addConstraint:[NSLayoutConstraint constraintWithItem:self.leftLine attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.footerView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:10.f]];
    
    [self.labelTitle addConstraint:[NSLayoutConstraint constraintWithItem:self.labelTitle attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:20.f]];
    [self.labelTitle addConstraint:[NSLayoutConstraint constraintWithItem:self.labelTitle attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:SCREEN_WIDTH/3-20]];
    [self.footerView addConstraint:[NSLayoutConstraint constraintWithItem:self.labelTitle attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.footerView attribute:NSLayoutAttributeTop multiplier:1.0 constant:10.f]];
    [self.footerView addConstraint:[NSLayoutConstraint constraintWithItem:self.labelTitle attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.leftLine attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.f]];
    
    [self.rightLine addConstraint:[NSLayoutConstraint constraintWithItem:self.rightLine attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:0.5f]];
    [self.rightLine addConstraint:[NSLayoutConstraint constraintWithItem:self.rightLine attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:SCREEN_WIDTH/3]];
    [self.footerView addConstraint:[NSLayoutConstraint constraintWithItem:self.rightLine attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.footerView attribute:NSLayoutAttributeTop multiplier:1.0 constant:20.f]];
    [self.footerView addConstraint:[NSLayoutConstraint constraintWithItem:self.rightLine attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.footerView attribute:NSLayoutAttributeRight multiplier:1.0 constant:-10.f]];
    
    [self.btnQQ addConstraint:[NSLayoutConstraint constraintWithItem:self.btnQQ attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:40.f]];
    [self.btnQQ addConstraint:[NSLayoutConstraint constraintWithItem:self.btnQQ attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:40.f]];
    [self.footerView addConstraint:[NSLayoutConstraint constraintWithItem:self.btnQQ attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.labelTitle attribute:NSLayoutAttributeBottom multiplier:1.0 constant:10.f]];
    [self.footerView addConstraint:[NSLayoutConstraint constraintWithItem:self.btnQQ attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.footerView attribute:NSLayoutAttributeRight multiplier:1.0 constant:-SCREEN_WIDTH/2-10]];
    
    [self.btnWeChat addConstraint:[NSLayoutConstraint constraintWithItem:self.btnWeChat attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:40.f]];
    [self.btnWeChat addConstraint:[NSLayoutConstraint constraintWithItem:self.btnWeChat attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:40.f]];
    [self.footerView addConstraint:[NSLayoutConstraint constraintWithItem:self.btnWeChat attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.labelTitle attribute:NSLayoutAttributeBottom multiplier:1.0 constant:10.f]];
    [self.footerView addConstraint:[NSLayoutConstraint constraintWithItem:self.btnWeChat attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.btnQQ attribute:NSLayoutAttributeRight multiplier:1.0 constant:20.f]];
    
    
    
}



#pragma mark =====================================================  通知
-(void)weChatLoginAuthorization:(NSNotification*)notification{
    NSDictionary* dict = [notification object];
    NSString* nickName = [dict objectForKey:@"nickname"];
    NSString* openID = [dict objectForKey:@"openid"];
    NSString* avatar = [dict objectForKey:@"headimgurl"];
    // 实现平台统一将openid 改成 unionid 的值
    openID = [dict objectForKey:@"unionid"];
    
    [self thirdPartyLogin:nickName openID:openID face:avatar type:2];
}

#pragma mark =====================================================  SEL
-(IBAction)closeView:(id)sender{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

-(IBAction)switchTouch:(id)sender{
    UIButton* btn = (UIButton*)sender;
    btn.selected = !btn.selected;
    self.txtPassword.secureTextEntry = !btn.selected;
}

-(IBAction)btnLoginTouch:(id)sender{
    [self checkNetWorkState:^(AFNetworkReachabilityStatus netWorkStatus) {
        if(netWorkStatus != AFNetworkReachabilityStatusNotReachable)
            if([self checkForm]){
                self.HUD = [[MBProgressHUD alloc] initWithView:self.view.window];
                [self.view.window addSubview:self.HUD];
                self.HUD.delegate = self;
                self.HUD.minSize = CGSizeMake(135.f, 135.f);
                [self.HUD setLabelFont:[UIFont systemFontOfSize:14.f]];
                self.HUD.labelText = @"正在登录!";
                [self.HUD show:YES];
                
                NSDictionary* arg = @{@"ince":@"user_login",@"uname":self.txtUserName.text,@"passwd":self.txtPassword.text};
                NetRepositories* repositories = [[NetRepositories alloc]init];
                [repositories login:arg complete:^(NSInteger react, id obj, NSString *message) {
                    if(react == 1){
                        MMember* entity = (MMember*)obj;
                        entity.isLogin = YES;
                        Boolean flag= [NSKeyedArchiver archiveRootObject:entity toFile:[WMHelper archiverPath]];
                        if(flag){
                            NSUserDefaults* config = [NSUserDefaults standardUserDefaults];
                            [config setObject:@(YES) forKey:kisBindingJPushTag];
                            [config synchronize];
                            [self registerTagsWithAlias:self.Identity.userInfo.userID];
                            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationLoginSuccess object:nil];
                        }else{
                           // NSLog(@"%@",@"归档失败!");
                        }
                        [self hidHUD:@"登录成功" success:YES];
                        [self dismissViewControllerAnimated:YES completion:nil];
                    }else if(react == 400){
                        [self hidHUD:message];
                    }else{
                        [self hidHUD:message];
                    }
                }];
                
            }
    }];
}

-(IBAction)registerTouch:(id)sender{
    Register* controller = [[Register alloc]init];
    [self.navigationController pushViewController:controller animated:YES];
}

-(IBAction)QQLoginTouch:(id)sender{
    [self checkNetWorkState:^(AFNetworkReachabilityStatus netWorkStatus) {
        if(netWorkStatus!=AFNetworkReachabilityStatusNotReachable){
            self.tencentOAuth= [[TencentOAuth alloc] initWithAppId:kQQAPP_ID andDelegate:self];
            NSArray  *permissions =  [NSArray arrayWithObjects:@"get_user_info", @"get_simple_userinfo", @"add_t", nil];
            [self.tencentOAuth authorize:permissions inSafari:NO];
            [self.tencentOAuth accessToken] ;
            [self.tencentOAuth openId] ;
                    }
    }];
    
}

-(IBAction)weiXinLoginTouch:(id)sender{
    [self checkNetWorkState:^(AFNetworkReachabilityStatus netWorkStatus) {
        if(netWorkStatus!=AFNetworkReachabilityStatusNotReachable){
            SendAuthReq* req =[[SendAuthReq alloc ] init ];
            req.openID = @"wxa63756a88befb156";
            req.scope = @"snsapi_userinfo" ;
            req.state = @"123" ;
            //第三方向微信终端发送一个SendAuthReq消息结构
            [WXApi sendReq:req];
        }
    }];
}
#pragma mark =====================================================  TencentSessionDelegate 协议实现
- (void)tencentDidLogin{
    [self.tencentOAuth getUserInfo];
}

- (void)tencentDidNotLogin:(BOOL)cancelled{
    if (cancelled)
    {
        [self alertHUD:@"用户取消登陆"];
    }
    else
    {
        [self alertHUD:@"登陆失败"];
    }
    
}

- (void)tencentDidNotNetWork{
    [self alertHUD:@"网络异常"];
}

-(void)getUserInfoResponse:(APIResponse *)response{
    //NSLog(@"%@",[response jsonResponse]);
    NSInteger flag = [[response.jsonResponse objectForKey:@"ret"] integerValue];
    if(flag == 0){
        NSString* openID = self.tencentOAuth.openId;
        NSString* nick = [response.jsonResponse objectForKey:@"nickname"];
        NSString* face = [response.jsonResponse objectForKey:@"figureurl_qq_2"];
        [self thirdPartyLogin:nick openID:openID face:face type:1];
    }else {
        [self alertHUD:@"授权失败"];
    }
}

#pragma mark =====================================================  绑定极光推送

-(void)registerTagsWithAlias:(NSString*)userID{
    
    __autoreleasing NSMutableSet *tags = [NSMutableSet set];
    __autoreleasing NSString *alias = userID;
    [self analyseInput:&alias tags:&tags];
    
    [JPUSHService setTags:tags alias:alias fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
        //NSLog(@"TagsAlias回调:\n iResCode:%d  iAlias:%@",iResCode,iAlias);
        if(iResCode == 0){
            
        }else{
            /* UIAlertView* alert = [[UIAlertView alloc]initWithTitle:nil message:@"消息推送注册失败,请退出后再登录!" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
             [alert show];*/
        }
    }];
}

- (void)setTags:(NSMutableSet **)tags addTag:(NSString *)tag {
    [*tags addObject:tag];
}

- (void)analyseInput:(NSString **)alias tags:(NSSet **)tags {
    // alias analyse
    if (![*alias length]) {
        // ignore alias
        *alias = nil;
    }
    // tags analyse
    if (![*tags count]) {
        *tags = nil;
    } else {
        __block int emptyStringCount = 0;
        [*tags enumerateObjectsUsingBlock:^(NSString *tag, BOOL *stop) {
            if ([tag isEqualToString:@""]) {
                emptyStringCount++;
            } else {
                emptyStringCount = 0;
                *stop = YES;
            }
        }];
        if (emptyStringCount == [*tags count]) {
            *tags = nil;
        }
    }
}
#pragma mark =====================================================  私有方法
-(void)thirdPartyLogin:(NSString*)nick openID:(NSString*)openID face:(NSString*)face type:(NSInteger)type{
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view.window];
    [self.view.window addSubview:self.HUD];
    self.HUD.delegate = self;
    self.HUD.minSize = CGSizeMake(135.f, 135.f);
    [self.HUD setLabelFont:[UIFont systemFontOfSize:14.f]];
    self.HUD.labelText = @"正在登录!";
    [self.HUD show:YES];
    
    
    NSDictionary* arg = @{@"ince":@"the_third_reg",@"nickname":nick,@"openid":openID,@"face_pic":face,@"type":[WMHelper integerConvertToString:type]};
    
    NetRepositories* repositories = [[NetRepositories alloc]init];
    [repositories login:arg complete:^(NSInteger react, id obj, NSString *message) {
        if(react == 1){
            MMember* entity = (MMember*)obj;
            entity.isLogin = YES;
            Boolean flag= [NSKeyedArchiver archiveRootObject:entity toFile:[WMHelper archiverPath]];
            if(flag){
                NSUserDefaults* config = [NSUserDefaults standardUserDefaults];
                [config setObject:@(YES) forKey:kisBindingJPushTag];
                [config synchronize];
                [self registerTagsWithAlias:self.Identity.userInfo.userID];
                [[NSNotificationCenter defaultCenter]postNotificationName:NotificationLoginSuccess object:nil];
            }else{
               // NSLog(@"%@",@"归档失败!");
            }
            [self hidHUD:@"登录成功" success:YES];
            [self dismissViewControllerAnimated:YES completion:nil];
        }else if(react == 400){
            [self hidHUD:message];
        }else{
            [self hidHUD:message];
        }
    }];
    
    
}

-(BOOL)checkForm{
    if([WMHelper isEmptyOrNULLOrnil:self.txtUserName.text]){
        [self alertHUD:@"用户名不能为空"];
        return NO;
    }else if([WMHelper isEmptyOrNULLOrnil:self.txtPassword.text]){
        [self alertHUD:@"密码不能为空"];
        return NO;
    }
    return YES;
}

@end
